package com.marvels.approve.loan.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.marvels.approve.consum.ApproveConsumerProductApi;
import com.marvels.approve.loan.dao.IMcamLoanApplyInfoDao;
import com.marvels.approve.loan.dto.McamLoanApplyInfoDTO;
import com.marvels.approve.loan.service.ILoanDecisionService;
import com.marvels.approve.loan.service.IMcamLoanApplyInfoService;
import com.marvels.approve.mqueues.dto.LoanApplyQueueDTO;
import com.marvels.approve.mqueues.service.ApproveILoanApplyQueueService;
import com.marvels.approve.process.consum.ConsumerDecisionExecuteApi;
import com.marvels.approve.process.dto.McptCustomerTypeParamDTO;
import com.marvels.approve.process.dto.McptProductMappedDto;
import com.marvels.approve.process.dto.StrategyResponseDTO;
import com.marvels.common.dto.MarvelsResultDTO;
import com.marvels.common.exception.MarvelsBusinessException;
import com.marvels.common.utils.MarvelsLogUtil;
@Service
public class LoanDecisionServiceImpl implements ILoanDecisionService {
	@Autowired
	private IMcamLoanApplyInfoService mcamLoanApplyInfoService ;
	@Autowired
	private ApproveILoanApplyQueueService loanApplyQueueService;
	@Autowired
	private ConsumerDecisionExecuteApi consumerDecisionExecuteApi ;
	@Autowired
	private IMcamLoanApplyInfoDao mcamLoanApplyInfoDao ;
	@Autowired
	private ApproveConsumerProductApi consumerProductApi ;
	// 该处不能加事务
	public int executeDecision() throws MarvelsBusinessException {
		// TODO 自动生成的方法存根
		LoanApplyQueueDTO loanApplyQueue = new LoanApplyQueueDTO();
		loanApplyQueue.setStatus(0);
		List<LoanApplyQueueDTO> loanApplyQueues = loanApplyQueueService.findLoanApplyQueueService(loanApplyQueue);
		// McamLoanApplyInfoDTO dto = new McamLoanApplyInfoDTO();
		// List<McamLoanApplyInfoDTO> applys = mcamLoanApplyInfoDao.select(dto);
		if (loanApplyQueues == null) {
			return 0;
		}
		int size = loanApplyQueues.size();
		MarvelsLogUtil.getInstance().info("执行决策数量execute_decision_size>" + size);
		int count = 0;
		// 一下调用决策接口/方法
		for (LoanApplyQueueDTO applyQueue : loanApplyQueues) {
			// 同步数据以及跑决策
			MarvelsLogUtil.getInstance().info("同步数据以及跑决策LoanId:" + applyQueue.getLoanId());
			boolean isRun = false;
			try {
				isRun = mcamLoanApplyInfoService.initProcessData(applyQueue);
			} catch (Exception e) {
				MarvelsLogUtil.getInstance().error("同步数据以及跑决策loanId:" + applyQueue.getLoanId() + "处理失败，失败原因：", e);
			}
			if (isRun) {
				count++;
			}
		}
		return count;
	}
	@Override
	public Boolean runCreditDecision(String loanId) throws MarvelsBusinessException {
		try {
			McamLoanApplyInfoDTO info = runCreditDecisionItem(loanId);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("跑决策异常",e);
			return false;
		}
		return true;
	}
	private void runProduct(String loanId,McamLoanApplyInfoDTO info) throws MarvelsBusinessException {
		McptProductMappedDto mapper = new McptProductMappedDto();
		mapper.setProductType(info.getProductType());
		mapper.setTenor(String.valueOf(info.getApplyTerms()));
		mapper.setGrate(info.getCreditRating());
		mapper.setChannel(info.getChannel());
		mapper.setFirstOrgCode(info.getChannelCodeLvOne());
		mapper.setSecondOrgCode(info.getChannelCodeLvTwo());
		mapper.setThirdOrgCode(info.getChannelCodeLvThree());
		MarvelsLogUtil.getInstance().info("路由产品小类失败；loanId:"+loanId+",ProductType:"+info.getProductType());
		MarvelsLogUtil.getInstance().info("路由产品小类失败；loanId:"+loanId+",ApplyTerms:"+info.getApplyTerms());
		MarvelsLogUtil.getInstance().info("路由产品小类失败；loanId:"+loanId+",CreditRating:"+info.getCreditRating());
		MarvelsLogUtil.getInstance().info("路由产品小类失败；loanId:"+loanId+",Channel:"+info.getChannel());
		MarvelsLogUtil.getInstance().info("路由产品小类失败；loanId:"+loanId+",ChannelCodeLvOne:"+info.getChannelCodeLvOne());
		MarvelsLogUtil.getInstance().info("路由产品小类失败；loanId:"+loanId+",ChannelCodeLvTwo:"+info.getChannelCodeLvTwo()); 
		MarvelsLogUtil.getInstance().info("路由产品小类失败；loanId:"+loanId+",ThirdWorkTypeCode:"+info.getThirdWorkTypeCode()); 
		List<Map> resultMap = getResultMap(mapper);
		if(resultMap != null && resultMap.size()>0) {
			Map productMap = resultMap.get(0);
			String productCode = (String)productMap.get("productCode");
			String productName = (String)productMap.get("productName");
			info.setProductCode(productCode);
			info.setProductName(productName);
		}else {
			throw new MarvelsBusinessException("路由产品小类失败；loanId:"+loanId+",评分:"+info.getCreditRating());
		}
	}
	//路由产品小类根据渠道迭代查询直到去掉3级渠道
	private List<Map> getResultMap(McptProductMappedDto mapper){
		MarvelsResultDTO result = consumerProductApi.searchByParams(mapper);//有3级渠道
		Object obj = result.getData();
		MarvelsLogUtil.getInstance().info("xxxxxxxxxxxxxxxxxxxxxx"+obj);
		List<Map> resultMap = (List<Map>)obj;
		if(resultMap == null || resultMap.size()==0) {
			mapper.setThirdOrgCode(null); 
			result = consumerProductApi.searchByParams(mapper);//去掉第三级渠道
			obj = result.getData();
			resultMap = (List<Map>)obj;
			if(resultMap == null || resultMap.size()==0) {
				mapper.setSecondOrgCode(null);
				result = consumerProductApi.searchByParams(mapper);//去掉第二级渠道
				obj = result.getData();
				resultMap = (List<Map>)obj;
				if(resultMap == null || resultMap.size()==0) {
					mapper.setFirstOrgCode(null);
					result = consumerProductApi.searchByParams(mapper);//去掉一级渠道
					obj = result.getData();
					resultMap = (List<Map>)obj;
				}
			}
		}
		return resultMap;
	}
	//跑决策加载静态文件
	private McamLoanApplyInfoDTO runCreditDecisionItem(String loanId)  throws MarvelsBusinessException {
		MarvelsLogUtil.getInstance().info(loanId+"跑决策加载静态文件");
		McamLoanApplyInfoDTO info = mcamLoanApplyInfoDao.selectMcamLoanApplyInfoByLoanId(loanId);
//		StrategyResponseDTO response = consumerDecisionExecuteApi.getDecisionResult(loanId, info.getProductType());
//		Double score = response.getXiaoDScore();
		Double score = 1d;
		if(score==null || score==0) {
			throw new MarvelsBusinessException("决策等级异常"+score);
		}
		List<McptCustomerTypeParamDTO> custTypes = consumerProductApi.selectAllType();
		String creditRating = "D";
		for(McptCustomerTypeParamDTO ctype:custTypes) {
			String ruleLvl = ctype.getRuleLvl();
			String decScore = String.valueOf(score==null?"":score);
			if(decScore.equals(ruleLvl)) {
				creditRating = ctype.getCustomerType();
			}
		}
		MarvelsLogUtil.getInstance().info(loanId+"跑决策等级creditRating:"+creditRating+",score:"+score);
		info.setCreditRating(creditRating);
		info.setRiskCustomerType(creditRating);
		
		//路由产品小类
		runProduct(loanId,info);
		mcamLoanApplyInfoDao.updateApplyInfo(info);
		return info;
	}
}
